using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace EntLibContrib.Common.Configuration
{
    /// <summary>
    /// Defines a configuration element that can be uniquely identified without having to define its name explicitly.
    /// </summary>
    public class AnonymousConfigurationElement : ConfigurationElement, IObjectWithName
    {
        private string name;

        #region IObjectWithName Members

        /// <summary>
        /// Gets the Name.
        /// </summary>
        public virtual string Name
        {
            get 
            {
                if (string.IsNullOrEmpty(name))
                {
                    name = Guid.NewGuid().ToString();
                }

                return name; 
            }
        }

        #endregion

        protected override void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode)
        {
            base.Unmerge(sourceElement, parentElement, saveMode);

            AnonymousConfigurationElement castedSourceElement = (AnonymousConfigurationElement)sourceElement;

            name = castedSourceElement.Name;
        }
    }
}
